package crew.blt.handsound.client.widgets.user;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import crew.blt.handsound.client.widgets.AuthTypeListBox;
import crew.blt.handsound.server.security.AppRole;
import crew.blt.handsound.shared.domain.Auth;
import crew.blt.handsound.shared.domain.User;
import crew.gwt.client.widgets.EntityContainer;
import crew.gwt.client.widgets.util.EntityPanel;

public class UserPanel extends Composite implements EntityPanel<User> {
	
	@UiTemplate("UserPanel.ui.xml")
	interface MPPanelUIBinder extends UiBinder<Widget, UserPanel> {}
	private static MPPanelUIBinder uiBinder = GWT.create(MPPanelUIBinder.class);

	//Attributes
	@UiField TextBox username;
	@UiField TextBox firstname;
	@UiField TextBox lastname;
	@UiField PasswordTextBox password;
	@UiField Button changePwBt;
	@UiField TextBox email;
	@UiField CheckBox enabled;
	//Auth
	@UiField AuthTypeListBox listAllAuth;
	@UiField EntityContainer<Auth> listUserAuth;
	@UiField Button addAuthBt;
	@UiField Button rmAuthBt;
	
	private User entity = new User();
	
	public UserPanel() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	//---------------------------------------------------------------------
	//-------------------------- UI Action	
	private void setPanel(){
		username.setText(entity.getUsername());
		firstname.setText(entity.getFirstName());
		lastname.setText(entity.getLastName());
		email.setText(entity.getEmail());
		enabled.setValue(entity.isEnabled());
	}
	
	public void clear() {
		entity = new User();
		username.setText("");
		firstname.setText("");
		lastname.setText("");
		email.setText("");
		enabled.setValue(false);
	}
	
	public void setReadOnly(boolean readOnly){
		username.setReadOnly(readOnly);
		firstname.setReadOnly(readOnly);
		lastname.setReadOnly(readOnly);
		email.setReadOnly(readOnly);
		enabled.setEnabled(!readOnly);
	}
	
	@Override
	public void setEditMode(boolean isEditMode){
		username.setReadOnly(isEditMode);
	}

	//---------------------------------------------------------------------
	//-------------------------- Handler
	
	public void setEntity(User entity){
		this.entity = entity;
		setPanel();
	}

	public User getEntity() {
		return entity;
	}

	@Override
	public boolean applyChangeOnEntity() {
		entity.setUsername(username.getText());
		entity.setFirstName(firstname.getText());
		entity.setLastName(lastname.getText());
		entity.setEmail(email.getText());
		entity.setEnabled(enabled.getValue());
		return true;
	}
}
